package com.atguigu.grainmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.grainmall.auth.feign.MemberFeignService;
import com.atguigu.grainmall.auth.feign.ThirdPartFeignService;
import com.atguigu.grainmall.auth.utils.RandomDemo;
import com.atguigu.grainmall.auth.vo.UserLoginVo;
import com.atguigu.grainmall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Author shiyuan
 * @Date 2023/3/10 16:03
 * @Version 1.0
 * 登录与注册
 **/
@Controller
public class LoginController {

//    @GetMapping("login.html")
//    public String loginPage(){
//
//        return "login";
//    }
//    注释部分已抽取到 视图映射中
//    @GetMapping("reg.html")
//    public String regPage(){
//
//        return "reg";
//    }

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 请求发送验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        if (StringUtils.isEmpty(phone)) {
            return R.error("请检查手机号码是否输入错误");
        }
        // 接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PERFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long lCodeTiem = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - lCodeTiem < 60000) {
                // 60妙内不可再次发送
                return R.error(BizCodeEnum.MSM_CODE_EXCEPTION.getCode(), BizCodeEnum.MSM_CODE_EXCEPTION.getMsg());
            }
        }
//        String code = UUID.randomUUID().toString().substring(0, 5);
        String code = RandomDemo.getRandom(100000, RandomDemo.TYPE.NUMBER).substring(0, 5);
        // 验证码的再次校验， 将手机号与验证码存入redis
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PERFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);

        return R.ok();
    }

    /**
     * 注册处理
     * RedirectAttributes 模拟解决网页重定向后 数据域数据共享问题
     * 利用session存储数据重定向后再取出来，但是存取只有一次，再次刷新页面皆会失效
     * #todo 分布式下使用session会出现问题
     * model重定向不可携带原有数据
     *
     * @param vo
     * @param result
     * @return
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        // 判断校验有无异常
        if (result.hasErrors()) {
            //获取所有字段出现的错误信息
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            // 如果校验出错 直接转发到注册页
            return "redirect:http://auth.grainmall.com/reg.html";
        }
        // 无异常直接远程调用进行注册
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PERFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                // 检验成功直接删除验证码  令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PERFIX + vo.getPhone());
                // 验证码检验通过 去注册
                R register = memberFeignService.register(vo);
                if (register.getCode() == 0) {
                    // 注册成功回到登录页或者首页
                    return "redirect:http://auth.grainmall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    // 出现错误或异常 直接转发到注册页
                    return "redirect:http://auth.grainmall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                // 校验出错 直接转发到注册页
                return "redirect:http://auth.grainmall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错 直接转发到注册页
            return "redirect:http://auth.grainmall.com/reg.html";
        }
        // 注册成功回到登录页或者首页
//        return "redirect:/login.html";
    }

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {

        // 远程登陆
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(LOGIN_USER,data);
            return "redirect:http://grainmall.com";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.grainmall.com/login.html";
        }
    }

    /**
     * 登陆成功后再次访问登录页只能跳转至首页
     * @param session
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(LOGIN_USER);
        if (attribute == null){
            return "login";
        }else {
            return "redirect:http://grainmall.com";
        }
    }
}
